package com.shujia.MR.combine;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.CombineTextInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class CombineDriver {
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {

        Configuration conf = new Configuration();
        // 创建一个Job
        Job job = Job.getInstance(conf);

        job.setJarByClass(CombineDriver.class);
        job.setJobName("Combine");

        // 设置Mapper及Reducer类
        job.setMapperClass(CombineMapper.class);
        job.setReducerClass(CombineReducer.class);

        // 设置Map方法输出类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);

//        job.setNumReduceTasks(2);

        // 设置最终输出类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);


        /**
         * 设置输出的类，要求是InputFormat子类
         *  Class<? extends InputFormat> cls
         *
         *  conf.setClass(INPUT_FORMAT_CLASS_ATTR, cls,
         *                   InputFormat.class);
         *
         *  INPUT_FORMAT_CLASS_ATTR = "mapreduce.job.inputformat.class";
         *
         *  public void setClass(String name, Class<?> theClass, Class<?> xface) {
         *     如果 传入的theClass 不是xface（InputFormat.class）的子类就主动抛出 RuntimeException异常
         *     if (!xface.isAssignableFrom(theClass))
         *       throw new RuntimeException(theClass+" not "+xface.getName());
         *     set(name, theClass.getName());
         *   }
         *
         */
        job.setInputFormatClass(CombineTextInputFormat.class);

        /**
         * 该方法内部实现逻辑：
         *  job.getConfiguration().setLong(SPLIT_MAXSIZE, size);
         *  通过修改SPLIT_MAXSIZE=mapreduce.input.fileinputformat.split.maxsize 来调小切片大小
         *
         *  size大小设置为4M = 1024 * 1024 * 4
         */
        CombineTextInputFormat.setMaxInputSplitSize(job,4194304);


        // 设置数据源以及输出结果,注意选择 org.apache.hadoop.mapreduce.lib.input.FileInputFormat
        FileInputFormat.addInputPath(job, new Path("D:\\workspace19\\HadoopCode\\data\\combine"));
        FileOutputFormat.setOutputPath(job, new Path("D:\\workspace19\\HadoopCode\\output\\combine"));

        // 提交
        job.waitForCompletion(true);
    }
}
